# coding=utf-8
import sys,redis
import configparser
import logging
import os
import time
from GetRtspData_0921 import GetRtspData



def get_logger(camera_id, rtsp_type):
    # 第一步，创建一个logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)  # Log等级总开关
    # 第二步，创建一个handler，用于写入日志文件
    rq = str(time.strftime('%Y%m%d', time.localtime(time.time()))) + '_' + str(camera_id) + '_' + str(rtsp_type)
    log_path = '/DATA01/app/common_rtsp/logs/1/'
    # log_path = '/opt/python' + '/logs/'
    # print('log_path', log_path)
    if not os.path.exists(log_path):
        os.mkdir(log_path)

    log_name = log_path + rq + '_receive.log'
    logfile = log_name
    fh = logging.FileHandler(logfile)
    fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关
    # 第三步，定义handler的输出格式
    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    fh.setFormatter(formatter)
    # 第四步，将logger添加到handler里面
    logger.addHandler(fh)
    return logger

if __name__ == '__main__':
    print('python run:', sys.argv)
    # 首先获取配置文件中的配置信息
    cf = configparser.ConfigParser()
    cf.read('/DATA01/app/common_rtsp/conf/application_1.ini')
    redisHost = cf.get("redis", 'host')
    redisDb = cf.get("redis", "db")
    redisPort = cf.get("redis", "port")
    redisPassword = cf.get("redis", "password")
    threadDefaultWorker = int(cf.get("thread", "defaultWorker"))

    if not all([redisHost, redisDb, redisPort, threadDefaultWorker]):
        print('参数配置不能为空')
        sys.exit(0)
    if not redisPassword:
        pool = redis.ConnectionPool(host=redisHost, port=redisPort, password=redisPassword, db=redisDb, decode_responses=False)
    else:
        pool = redis.ConnectionPool(host=redisHost, port=redisPort, password=redisPassword,db=redisDb, decode_responses=False)

    # 开始时间
    _time_start = int(sys.argv[1])
    camera_id = sys.argv[2]
    # 保存位置
    save_path = sys.argv[3]  # D:\\develop\\python\\camera_data\\photos
    # 这个不用管
    cam_channel = 'rtsp://admin:wanji123@10.100.16.1:554/cam/realmonitor?channel=1&subtype=0'
    # _time = int(get_now_milli_time() / 1000) - 5
    retained_time = 0


    r = redis.Redis(connection_pool=pool)

    # new_time = int(r.get(str(camera_id)))
    # if _time_start > new_time:
    #     print("当前redis中未存储该时间段数据", "start_time: ", _time_start, "new_time", new_time)
    #     _time_start = new_time -6

    _time_end = _time_start + 1

    print('_time_start:', _time_start, 'camera_id:', camera_id, 'save_path:', save_path)
    analysis_logger = get_logger(camera_id, 0)

    with GetRtspData(cam_channel, camera_id, retained_time,analysis_logger) as sgg:
        sgg.analysis_img3(camera_id, _time_start, _time_end, save_path, pool,threadDefaultWorker)
